<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['module:productrule:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['module:productrule:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['module:productrule:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规格值" align="center" prop="id" v-if="false"/>
      <el-table-column label="规格名称" align="center" prop="ruleName"/>
      <el-table-column label="规格值" align="center" prop="ruleValueArray">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.ruleValueArray">
            {{ item.value }} : {{ item.detail.join(',')}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['module:productrule:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['module:productrule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改商品规则值(规格)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="标题名称：" prop="ruleName">
              <el-input placeholder="请输入标题名称" v-model="form.ruleName" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="23" v-for="(item, index) in form.ruleValueArray" :key="index">
            <el-form-item label=" ">
              <div class="acea-row row-middle"><span class="mr5">{{item.value}}</span>
                <i class="el-icon-circle-close"  @click="handleRemove(index)"/>
              </div>
              <div class="rulesBox">
                <el-tag class="mb5" style="margin: 2px 4px 2px 0;" closable v-for="(j, indexn) in item.detail" :key="indexn"
                          :name="j" @close="handleRemove2(item.detail,indexn)" size="mini">
                  {{j}}
                </el-tag>
              </div>
              <el-input placeholder="请输入属性名称" v-model="item.detail.attrsVal" style="width: 250px" size="mini">
                <el-button slot="append" type="primary" @click="createAttr(item.detail.attrsVal,index)" size="mini">添加</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isBtn">
            <el-col :span="8">
              <el-form-item label="规格：">
                <el-input placeholder="输入规格" v-model="attrsName" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格值：">
                <el-input v-model="attrsVal" placeholder="输入规格值" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" size="mini" @click="createAttrName">保存</el-button>
              <el-button size="mini" @click="offAttrName">取消</el-button>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isBtn" size="mini" type="primary" @click="onAttrName">添加新规格</el-button>
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRule, getRule, delRule, addRule, updateRule } from "@/api/module/product/rule";

export default {
  name: "Rule",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规则值(规格)表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      attrsName: '',
      attrsVal: '',
      formNameData: [],
      isBtn: false,
      formName: [],
      ids: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ],
        ruleValue: [
          { required: true, message: "规格值不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品规则值(规格)列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then(response => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消
    onAttrName () {
      this.isBtn = true;
    },
    // 取消
    offAttrName () {
      this.isBtn = false;
    },
    // 删除
    handleRemove (index) {
      this.form.ruleValueArray.splice(index, 1);
    },
    // 删除属性
    handleRemove2 (item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName () {
      if (this.attrsName && this.attrsVal) {
        let data = {
          value: this.attrsName,
          detail: [
            this.attrsVal
          ]
        };
        this.form.ruleValueArray.push(data);
        var hash = {};
        this.form.ruleValueArray = this.form.ruleValueArray.reduce(function (item, next) {
          /* eslint-disable */
          hash[next.value] ? '' : hash[next.value] = true && item.push(next);
          return item
        }, []);
        this.attrsName = '';
        this.attrsVal = '';
        this.isBtn = false;
      } else {
        return this.$message.warning('请添加规格名称！');
      }
    },
    // 添加属性
    createAttr (num, idx) {
      if (num) {
        this.form.ruleValueArray[idx].detail.push(num);
        var hash = {};
        this.form.ruleValueArray[idx].detail = this.form.ruleValueArray[idx].detail.reduce(function (item, next) {
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
      } else {
        return this.$message.warning('请添加属性！');
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.form.ruleValueArray = [];
      this.isBtn = false;
      this.attrsName = '';
      this.attrsVal = '';
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ruleName: undefined,
        createTime: undefined,
        updateTime: undefined,
        isDel: undefined,
        ruleValue:undefined,
        ruleValueArray:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品规则值(规格)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getRule(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改商品规则值(规格)";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateRule(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRule(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品规则值(规格)编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delRule(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },

  }
};
</script>
